package zuosheng.day5;

/**
 * @author lj
 * @Description:
 * @date 2020-11-04 22:14
 * @QQ 851477108
 */


public class RotateMatrix {
    public static void main(String[] args) {
        int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };
        printMatrix(matrix);
        rotate(matrix);
        System.out.println("=========");
        printMatrix(matrix);
    }

    public static void rotate(int[][] m){
        int tR = 0;
        int tC = 0;
        int dR = m.length - 1;
        int dC = m[0].length - 1;
        while (tR < dR){
            rotateEdge(m,tR++,tC++,dR--,dC--);
        }
    }

    public static void rotateEdge(int[][] m, int tR, int tC, int dR, int dC){
        int times = dR - tR;
        for (int i = 0; i != times; i++){
            int tmp = m[tR + i][tC];
            m[tR + i][tC] = m[dR][tC + i];
            m[dR][tC + i] = m[dR - i][dC];
            m[dR - i][dC] = m[tR][dC - i];
            m[tR][dC - i] = tmp;
        }
    }

    public static void printMatrix(int[][] m){
        for (int i = 0; i != m.length; i++) {
            for (int j = 0; j !=m[0].length; j++){
                System.out.print(m[i][j]+" ");
            }
            System.out.println();
        }
    }
}
